package com.tianji.aigc.tools;

import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.tianji.aigc.config.ToolResultHolder;
import com.tianji.aigc.constants.Constant;
import com.tianji.aigc.tools.result.PrePlaceOrder;
import com.tianji.api.client.trade.TradeClient;
import com.tianji.api.dto.trade.OrderConfirmVO;
import com.tianji.common.utils.UserContext;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.model.ToolContext;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Optional;

@RequiredArgsConstructor
@Component
public class OrderTools{

    private final TradeClient tradeClient;

    @Tool(description = Constant.Tools.PRE_PLACE_ORDER)
    public PrePlaceOrder prePlaceOrder(@ToolParam(description = Constant.ToolParams.COURSE_IDS) List<Number> courseIds,
                                       ToolContext toolContext){
        //设置用户id，因为大模型调用时跟用户自己取，不是一个线程，所以要设置用户id
        UserContext.setUser(Convert.toLong(toolContext.getContext().get(Constant.USER_ID)));
        OrderConfirmVO orderConfirmVO = tradeClient.prePlaceOrder(CollStreamUtil.toList(courseIds, Number::longValue));
        return Optional.ofNullable(orderConfirmVO)
                //转换成工具返回结果
                .map(PrePlaceOrder::of)
                //保存卡片参数
                .map(prePlaceOrder -> {
                    String requestId = Convert.toStr(toolContext.getContext().get(Constant.REQUEST_ID));
                    String field = StrUtil.lowerFirst(PrePlaceOrder.class.getSimpleName());
                    ToolResultHolder.put(requestId, field, prePlaceOrder);
                    return prePlaceOrder;
                })
                .orElse(null);
    }
}
